package com.will.yuaiagent.controller;

import com.will.yuaiagent.agent.Manus;
import com.will.yuaiagent.app.LoveApp;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

/**
 * @author will
 * @since 2025/7/25 18:25
 */
@RestController
@RequestMapping("/ai")
public class AiController {

    @Resource
    private LoveApp LoveApp;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatModel dashscopeChatModel;


    /**
     * 同步聊天
     */
    @GetMapping("love_app/chat/sync")
    public String doChatWithSync(String message, String chatId) {
        return LoveApp.doChat(message, chatId);
    }

    /**
     * SSE流式调用AI恋爱大师的应用
     */
    @GetMapping(value = "love_app/chat/sse",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatWithSSE(String message, String chatId) {
        return LoveApp.doChatByStream(message, chatId);
    }

    /**
     * SSE流式调用AI恋爱大师的应用
     */
    @GetMapping(value = "love_app/chat/server_sent_event")
    public Flux<ServerSentEvent<String>> doChatWithServerSentEvent(String message, String chatId) {
        return LoveApp.doChatByStream(message, chatId)
                .map(chunk -> ServerSentEvent.<String>builder()
                        .data(chunk)
                        .build());
    }

    /**
     * SSE流式调用AI恋爱大师的应用
     */
    @GetMapping(value = "love_app/chat/sse_emitter")
    public SseEmitter doChatWithServerSseEmitter(String message, String chatId) {
        SseEmitter emitter = new SseEmitter(180000L);//180秒超时
        return (SseEmitter) LoveApp.doChatByStream(message, chatId)
                .subscribe(chunk -> {
                    try {
                        emitter.send(chunk);
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                },emitter::completeWithError, emitter::complete);

    }

    /**
     * 流式调用Manus智能体
     * @param message 用户输入
     * @return 流式回复
     */
    @GetMapping("manus/chat")
    public SseEmitter doChatWithManus(String message) {
        Manus manus = new Manus(allTools, dashscopeChatModel);
        return manus.runStream(message);
    }

}
